package com.apache.workday;

import com.apache.tools.ConfigUtil;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import org.apache.log4j.Logger;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工作日工具类
 *
 * @author qmhao
 */
public class WorkdayUtils {
	protected Logger log = Logger.getLogger(this.getClass());
    /**
     * 工作日service
     */
    private static WorkdayUtils instance;

    private Map<String, WorkdayService> service = new HashMap<String, WorkdayService>();

    private String filePath = "";

    private WorkdayUtils() {
        filePath = ConfigUtil.getInstance().getValueByKey("workday_config_path");
		if (StrUtil.isNull(filePath)){
			log.info("workday_config_path统一配置中为空，读取本地！");
			filePath = ConfigUtil.getClassLoaderPath() + "config/";
		}
		log.info("workday_config_path->"+filePath);
		if (filePath.indexOf(".jar") == -1) {
			String filePathWorkday = filePath + "workday_config.json";
			boolean flag = checkFolder(filePathWorkday);
			if (!flag){
				log.error(filePathWorkday+"文件不存在["+flag+"]！！！！！！！！！！");
			}
        }
        service.put("default", new WorkdayService(filePath));
    }

    public static WorkdayUtils getInstance() {
        if (null == instance) {
            instance = new WorkdayUtils();
        }
        return instance;
    }

    public List<Workday> getDayList() {
        return getDayList("default");
    }

    public List<Workday> getDayList(String key) {
        return service.get(key).getDayList();
    }

    public Workday getDay(String yyyyMMdd) {
        return getDay("default", yyyyMMdd);
    }

    public Workday getDay(String key, String yyyyMMdd) {
        return service.get(key).getDay(yyyyMMdd);
    }

    /**
     * 设置和保存工作日
     *
     * @param yyyyMMdd
     * @param isWorkday T表示工作日 F表示休息日
     */
    public void setDay(String yyyyMMdd, boolean isWorkday) {
        setDay("default", yyyyMMdd, isWorkday);
    }

    /**
     * 设置和保存工作日
     *
     * @param yyyyMMdd
     * @param isWorkday T表示工作日 F表示休息日
     */
    public void setDay(String key, String yyyyMMdd, boolean isWorkday) {
        Workday dvo = new Workday();
        dvo.setDateStr(yyyyMMdd);
        dvo.setIsWorkday(isWorkday ? "T" : "F");
        service.get(key).setDay(dvo);
    }

    /**
     * 取到某年下的数据
     *
     * @param year 格式yyyy 例如getDayListOfYear("2012");
     * @return
     */
    public List<Workday> getDayListOfYear(String year) {
        return getDayListOfYear("default", year);
    }

    public List<Workday> getDayListOfYear(String key, String year) {
        return service.get(key).getDayListOfYear(year);
    }

    /**
     * 设置工作日，即保存工作日
     *
     * @param dvo
     */
    public void setDay(Workday dvo) {
        setDay("default", dvo);
    }

    public void setDay(String key, Workday dvo) {
        service.get(key).setDay(dvo);
    }

    public Map<String, Workday> getDayMap() {
        return getDayMap("default");
    }

    public Map<String, Workday> getDayMap(String key) {
        return service.get(key).getDayMap();
    }

    public boolean isWorkday(String yyyyMMdd) {
        return isWorkday("default", yyyyMMdd);
    }

    public boolean isWorkday(String key, String yyyyMMdd) {
        Workday workday = instance.getDay(yyyyMMdd);
        if (null == workday) {
            return true;
        }
        return "T".equals(workday.getIsWorkday());
    }

    /**
     * 得到若干工作日之后的日期
     *
     * @param startDayStr 起始日期
     * @param n 工作日数
     * @return 起始日期 + 工作日数后的日期串
     */
    public String afterWorkday(String startDayStr, int n) throws Exception {
        Date start = DateUtils.strToDate(startDayStr, "yyyy-MM-dd");
        //		String yearStr = DateUtils.format(start, "yyyy");
        String dayStr = new SimpleDateFormat("yyyyMMdd").format(start);

        String endStr = getEndWorkdayStr1(n, dayStr);
        return endStr;

    }

    /**
     * 得到若干工作日之后的日期
     *
     * @param start 开始日期
     * @param n 几个工作日
     * @return
     */
    public Date afterWorkday(Date start, int n) throws Exception {
        String dayStr = DateUtils.format(start, "yyyyMMdd");

        String endStr = getEndWorkdayStr1(n, dayStr);
        return DateUtils.parse(endStr, "yyyyMMdd");
    }

    /**
     * 计算工作日，根据存储的工作日库，推算
     *
     * @param n
     * @param dayStr
     * @return
     */
    private String getEndWorkdayStr1(int n, String dayStr) throws Exception {
        if (n <= 0) {
            return dayStr;
        }
        String endStr = "";
        List<Workday> list = getDayList();
        int flag = 0;
        boolean countBegin = false;
        for (int i = 0; i < list.size(); i++) {
            Workday dvo = list.get(i);
            String afterDateStr = dvo.getDateStr();
            if (dayStr.equals(afterDateStr)) {
                countBegin = true;
                continue;
            }
            if (false == countBegin) {
                continue;
            }
            if ("T".equals(dvo.getIsWorkday())) {
                flag++;
            }

            if (flag >= n) {
                endStr = afterDateStr;
                break;
            }
        }
        return endStr;
    }

    public void setWorkday(String key, WorkdayService value) {
        service.put(key, value);
    }

    /**
     * 检查文件或文件夹是否存在
     *
     * @param folderPath 文件或文件夹路径
     * @return true为存在，false不存在
     */
    public boolean checkFolder(String folderPath) {
        boolean result = false;
        if (StrUtil.isNotNull(folderPath)) {
            File newFilePath = new File(folderPath);
            result = newFilePath.exists();
        }
        return result;
    }

}
